"""this use FileReader to decode counter"""

import os
import re
import sys

import logging
import subprocess
import _subprocess


FILE_READER = "FileReader.exe"
INI = "pmmeaconfig.ini"


IS_WIN32 = 'win32' in str(sys.platform).lower() 

def sub_popen(cmd, **kwargs):
    if IS_WIN32:  
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = _subprocess.CREATE_NEW_CONSOLE | \
                              _subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = _subprocess.SW_HIDE
        kwargs['startupinfo'] = startupinfo

    return subprocess.Popen(cmd, **kwargs)

def call_file_reader(args):
    cwd = os.path.join(os.getcwd(), "tools")
    p = logging.getLogger('log.readfile')
    file_reader = os.path.join(cwd, FILE_READER)
    if not os.path.isfile(file_reader):
        p.error("read file tool(%s) is not exist." % file_reader)
        return False
    
    ini_file = os.path.join(cwd, INI)
    if not os.path.isfile(ini_file):
        p.error("read measurement config file(%s) is not exist." % ini_file)
        return False
    
    cmd = "%s -n %s %s" %(file_reader, ini_file, args)

    p.debug(cmd)
    del p

    proc = sub_popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait()
    return pick_counter(proc.stderr.read())

def decode_file(D00):
    if not os.path.isfile(D00):
        p = logging.getLogger('log.counter_decode')
        p.error("decode file %s not found." % D00)
        del p
        return None

    args = " -q -z -i " + D00
    return call_file_reader(args)

def decode_crnc(ip, filenames, outputfile):
    args = " -f %s -i %s -r -q -z -o %s" % (ip, filenames, outputfile)
    return call_file_reader(args)

def pick_counter(stderr):
    
    p = logging.getLogger('log.pick_counter')
    p.debug(stderr)

    counters = []
    for line in stderr.splitlines():
        if "Reading counter names" in line:
            counters.append(re.findall(r"measurement (\d{4})", line)[0])
    if counters:
        return ", ".join(sorted(list(set(counters))))
    else:
        p.warn("no measurement decode.")
        return None
    
    